package com.noranj.web.client;

import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.Widget;
import com.noranj.web.shared.DocumentDTO;

public class MainPanel extends Composite {

	private static MainPanelUiBinder uiBinder = GWT
			.create(MainPanelUiBinder.class);

	interface MainPanelUiBinder extends UiBinder<Widget, MainPanel> {
	}

    @UiField
     ScrollPanel mainPanel;
	  
	private List<DocumentDTO> documentDTOs;
	private final DocumentsServiceAsync documentsService = GWT
		      .create(DocumentsService.class);  
	
	public MainPanel() {
		initWidget(uiBinder.createAndBindUi(this));
		getDocuments();
	}

	 private void setDocuments(List<DocumentDTO> documentDTOs) {
		    this.documentDTOs = documentDTOs;
		  }
	 
	 public void showDocuments() {
		    mainPanel.clear();
		    mainPanel.add(new DocumentListView(documentDTOs));
		  }
	 
	 protected void setAndShowMessages(List<DocumentDTO> documentDTOs) {
		    setDocuments(documentDTOs);
		    showDocuments();
		  }
	 
	 public void getDocuments() {
		 documentsService.getDocuments(null, new AsyncCallback<List<DocumentDTO>>() {
		      public void onFailure(Throwable caught) {
		        Window.alert("An error occurred");
		      }

		      public void onSuccess(List<DocumentDTO> documentDTOs) {
		        setAndShowMessages(documentDTOs);

		      }
		    });
		  }
}
